﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;
using Furion;
using Furion.RemoteRequest.Extensions;
using Serilog;
using HttpMethod = System.Net.Http.HttpMethod;

namespace Admin.NET.Application
{
    /// <summary>
    /// 退库单服务
    /// </summary>
    [ApiDescriptionSettings("自己的业务", Name = "WmsStockReturnOrder", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsStockReturnOrderService : IWmsStockReturnOrderService, IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsStockReturnOrder,MasterDbContextLocator> _wmsStockReturnOrderRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();
        private readonly IRepository<WmsStockReturnOrderDetails, MasterDbContextLocator> _wmsStockReturnOrderDetailsRep;
        private readonly IRepository<WmsTakeMaterialOrderDetail, MasterDbContextLocator> _wmsTakeMaterialOrderDetailRep;
        private readonly IRepository<WmsOrderType, MasterDbContextLocator> _wmsOrderTypeRep;


        public WmsStockReturnOrderService(
            IRepository<WmsStockReturnOrder,MasterDbContextLocator> wmsStockReturnOrderRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,ISysExcelTemplateService sysExcelTemplateService
            , IRepository<WmsStockReturnOrderDetails, MasterDbContextLocator> wmsStockReturnOrderDetailsRep
            , IRepository<WmsTakeMaterialOrderDetail, MasterDbContextLocator> wmsTakeMaterialOrderDetailRep
            , IRepository<WmsOrderType, MasterDbContextLocator> wmsOrderTypeRep

        )
        {
            _wmsStockReturnOrderRep = wmsStockReturnOrderRep;
         _sysDictTypeRep = sysDictTypeRep;
         _sysDictDataRep = sysDictDataRep;
         _sysExcelTemplateService = sysExcelTemplateService;
            _wmsStockReturnOrderDetailsRep = wmsStockReturnOrderDetailsRep;
            _wmsTakeMaterialOrderDetailRep = wmsTakeMaterialOrderDetailRep;
            _wmsOrderTypeRep = wmsOrderTypeRep;
        }

        /// <summary>
        /// 分页查询退库单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsStockReturnOrderOutput>> Page([FromQuery] WmsStockReturnOrderSearch input)
        {
            var wmsStockReturnOrders = await _wmsStockReturnOrderRep.DetachedEntities
                                     .Where(input.MoveType != null, u => u.MoveType == input.MoveType)
                                     .Where(!string.IsNullOrEmpty(input.NO), u => EF.Functions.Like(u.NO, $"%{input.NO.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.WBSElementcode), u => EF.Functions.Like(u.WBSElementcode, $"%{input.WBSElementcode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.BenefitingDepartcode), u => EF.Functions.Like(u.BenefitingDepartcode, $"%{input.BenefitingDepartcode.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.CostCenterID), u => EF.Functions.Like(u.CostCenterID, $"%{input.CostCenterID.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.FI_Client_Analysis_H), u => EF.Functions.Like(u.FI_Client_Analysis_H, $"%{input.FI_Client_Analysis_H.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.PickerID), u => EF.Functions.Like(u.PickerID, $"%{input.PickerID.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.Companyname), u => EF.Functions.Like(u.Companyname, $"%{input.Companyname.Trim()}%"))
                                     .Where(!string.IsNullOrEmpty(input.ConstructionTeamID), u => EF.Functions.Like(u.ConstructionTeamID, $"%{input.ConstructionTeamID.Trim()}%"))
                                     .Where(input.OrderStatus != null, u => u.OrderStatus == input.OrderStatus)
                                     .OrderBy(PageInputOrder.OrderBuilder<WmsStockReturnOrderSearch>(input))
                                     .ProjectToType<WmsStockReturnOrderOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsStockReturnOrders;
        }

        /// <summary>
        /// 获取单据明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("PageDetail")]
        public async Task<PageResult<WmsStockReturnOrderDetailOutput>> PageDetail([FromQuery] PageDetailStockReturnOrderInput input)
        {
            var wmsOrders = await _wmsStockReturnOrderDetailsRep.DetachedEntities
                                     .Where(input.Id != null, u => u.OrderId == input.Id)
                                     .ProjectToType<WmsStockReturnOrderDetailOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsOrders;
        }

        /// <summary>
        /// 获取出库完成的明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("GetTakeOrderDetail")]
        public async Task<PageResult<WmsStockReturnOrderDetailOutput>> GetTakeOrderDetail([FromQuery] GetTakeOrderDetailInput input)
        {
            var wmsOrders = await _wmsTakeMaterialOrderDetailRep.DetachedEntities
                                      .Where(!string.IsNullOrEmpty(input.Materialcode), u => EF.Functions.Like(u.Materialcode, $"%{input.Materialcode.Trim()}%"))
                                      .Where(!string.IsNullOrEmpty(input.Materialname), u => EF.Functions.Like(u.Materialname, $"%{input.Materialname.Trim()}%"))
                                      .Where(!string.IsNullOrEmpty(input.Batchno_SCM), u => EF.Functions.Like(u.Batchno_SCM, $"%{input.Batchno_SCM.Trim()}%"))
                                      .Where(!string.IsNullOrEmpty(input.Batchno_WMS), u => EF.Functions.Like(u.Batchno_WMS, $"%{input.Batchno_WMS.Trim()}%"))
                                      .Where(!string.IsNullOrEmpty(input.ProjectCode), u => EF.Functions.Like(u.ProjectCode, $"%{input.ProjectCode.Trim()}%"))
                                      .Where(!string.IsNullOrEmpty(input.TACode), u => EF.Functions.Like(u.TACode, $"%{input.TACode.Trim()}%"))
                                      .Where(!string.IsNullOrEmpty(input.PartCode), u => EF.Functions.Like(u.PartCode, $"%{input.PartCode.Trim()}%"))
                                      .Where(x=>x.OrderStatus == OrderDetailsStatusEnum.WANCHENG)
                                     .ProjectToType<WmsStockReturnOrderDetailOutput>()
                                     .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsOrders;
        }

        /// <summary>
        /// 增加退库单(yigo系统获取)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        [UnitOfWork]
        public async Task Add()
        {
            //var wmsStockReturnOrder = input.Adapt<WmsStockReturnOrder>();
            //var wmsOrderType = await _wmsOrderTypeRep.FirstOrDefaultAsync(z => z.Name.Contains("退库申请"));
            //wmsStockReturnOrder.SOID = 66666;
            //wmsStockReturnOrder.OrderLargeCategory = wmsOrderType != null ? wmsOrderType.Pid : 0;
            //wmsStockReturnOrder.OrderSubclass = wmsOrderType != null ? wmsOrderType.Id : 0;
            //wmsStockReturnOrder.OrderStatus = OrderStatusEnum.WEIXIAFA;
            //await _wmsStockReturnOrderRep.InsertNowAsync(wmsStockReturnOrder);
            //foreach (var item in input.WmsStockReturnOrderDetails)
            //{
            //    var WmsStockReturnOrderDetailsModal = item.Adapt<WmsStockReturnOrderDetails>();
            //    WmsStockReturnOrderDetailsModal.OrderId = wmsStockReturnOrder.Id;
            //    await _wmsStockReturnOrderDetailsRep.InsertAsync(WmsStockReturnOrderDetailsModal);
            //}  
            //获取入库通知单
            string url = App.Configuration["YiGoWebApi:QueryReturnQuisition"];
            var Billdate_S = DateTime.Now.AddDays(-15).ToString("yyyy-MM-dd");
            var Billdate_E = DateTime.Now.AddDays(15).ToString("yyyy-MM-dd");
            //写日志文件
            //Log.Error($"[TransferContainerCode][ContainerCode:{input.ContainerCode}][url:{url}]");
            var response = await url.SetHttpMethod(System.Net.Http.HttpMethod.Post)
                                    .SetBody(new Dictionary<string, object> {
                                            { "Billdate_S", Billdate_S },
                                            { "Billdate_E", Billdate_E},
                                    }, "application/json").PostAsStringAsync();
            var Data = response.FromJson<WmsStockReturnOrderOutputByYiGO>();
            var wmsOrderType = await _wmsOrderTypeRep.FirstOrDefaultAsync(z => z.Name.Contains("物料退库"));
            foreach (var item in Data.Data)
            {
                item.Id = Yitter.IdGenerator.YitIdHelper.NextId();
                var wmsStockReturnOrder = item.Adapt<WmsStockReturnOrder>();
                var isExcit = await _wmsStockReturnOrderRep.AnyAsync(x => x.NO == item.NO);
                if (!isExcit)
                {
                    wmsStockReturnOrder.OrderLargeCategory = wmsOrderType != null ? wmsOrderType.Pid : 0;
                    wmsStockReturnOrder.OrderSubclass = wmsOrderType != null ? wmsOrderType.Id : 0;
                    await _wmsStockReturnOrderRep.InsertNowAsync(wmsStockReturnOrder);
                    foreach (var item1 in item.Dtls)
                    {
                        var wmsStockReturnOrderDeatail = item1.Adapt<WmsStockReturnOrderDetails>();
                        wmsStockReturnOrderDeatail.OrderId = item.Id;
                        await _wmsStockReturnOrderDetailsRep.InsertNowAsync(wmsStockReturnOrderDeatail);
                    }
                }
                
            }
        }

        /// <summary>
        /// 退料上架接口(yigo系统)
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("StockReturnGoodsReturnOrder")]
        [UnifyResult(typeof(object))]
        [UnitOfWork]
        public async Task<object> StockReturnGoodsReturnOrder([FromBody] StockReturnGoodsReturnOrderInput input)
        {
            try
            {
                //创建指定名称的订单操作
                string url = App.Configuration["YiGoWebApi:CreateTXRe111"];
                //获取主单据
                var wmsStockReturnOrderModal = await _wmsStockReturnOrderRep.FirstOrDefaultAsync(x => x.Id == input.Id);
                if (wmsStockReturnOrderModal == null) throw Oops.Oh("单据信息不存在!");
                // 写日志文件
                Log.Error($"[退料上架][单据号:{wmsStockReturnOrderModal.NO}][url:{url}]");

                var response = await url.SetHttpMethod(HttpMethod.Post)
                                        .SetBody(input, "application/json")
                                        .PostAsAsync<StockReturnGoodsReturnOrderOutput>();
                // 写日志文件
                Log.Error($"[退料上架][单据号:{wmsStockReturnOrderModal.NO}][response:{response.ToJson()}]");

                return XnRestfulResultProvider.RESTfulResult(response);
            }
            catch (Exception ex)
            {
                throw Oops.Oh(ex.Message);
            }
        }

        /// <summary>
        /// 不分页查询退库单列表
        /// </summary>
        /// <param name="input">退库单查询参数</param>
        /// <returns>(退库单)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsStockReturnOrderOutput>> ListNonPageAsync([FromQuery] WmsStockReturnOrderSearchNonPage input)
        {
            var pMoveType = input.MoveType;
            var pNO = input.NO?.Trim() ?? "";
            var pWBSElementcode = input.WBSElementcode?.Trim() ?? "";
            var pBenefitingDepartcode = input.BenefitingDepartcode?.Trim() ?? "";
            var pCostCenterID = input.CostCenterID?.Trim() ?? "";
            var pFI_Client_Analysis_H = input.FI_Client_Analysis_H?.Trim() ?? "";
            var pPickerID = input.PickerID?.Trim() ?? "";
            var pCompanyname = input.Companyname?.Trim() ?? "";
            var pConstructionTeamID = input.ConstructionTeamID?.Trim() ?? "";
            var pOrderStatus = input.OrderStatus;
            var wmsStockReturnOrders = await _wmsStockReturnOrderRep.DetachedEntities
                .Where(pMoveType != null, u => u.MoveType == pMoveType)
                .Where(!string.IsNullOrEmpty(pNO), u => EF.Functions.Like(u.NO, $"%{pNO}%")) 
                .Where(!string.IsNullOrEmpty(pWBSElementcode), u => EF.Functions.Like(u.WBSElementcode, $"%{pWBSElementcode}%")) 
                .Where(!string.IsNullOrEmpty(pBenefitingDepartcode), u => EF.Functions.Like(u.BenefitingDepartcode, $"%{pBenefitingDepartcode}%")) 
                .Where(!string.IsNullOrEmpty(pCostCenterID), u => EF.Functions.Like(u.CostCenterID, $"%{pCostCenterID}%")) 
                .Where(!string.IsNullOrEmpty(pFI_Client_Analysis_H), u => EF.Functions.Like(u.FI_Client_Analysis_H, $"%{pFI_Client_Analysis_H}%")) 
                .Where(!string.IsNullOrEmpty(pPickerID), u => EF.Functions.Like(u.PickerID, $"%{pPickerID}%")) 
                .Where(!string.IsNullOrEmpty(pCompanyname), u => EF.Functions.Like(u.Companyname, $"%{pCompanyname}%")) 
                .Where(!string.IsNullOrEmpty(pConstructionTeamID), u => EF.Functions.Like(u.ConstructionTeamID, $"%{pConstructionTeamID}%")) 
                .Where(pOrderStatus != null, u => u.OrderStatus == pOrderStatus)
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<WmsStockReturnOrderOutput>()
            .ToListAsync();
            return wmsStockReturnOrders;
        }


        

        /// <summary>
        /// 删除退库单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsStockReturnOrderInput input)
        {
            var wmsStockReturnOrder = await _wmsStockReturnOrderRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsStockReturnOrderRep.DeleteAsync(wmsStockReturnOrder);
        }

        /// <summary>
        /// 更新退库单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsStockReturnOrderInput input)
        {
            var isExist = await _wmsStockReturnOrderRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsStockReturnOrder = input.Adapt<WmsStockReturnOrder>();
            await _wmsStockReturnOrderRep.UpdateAsync(wmsStockReturnOrder,ignoreNullValues:true);
        }

        /// <summary>
        /// 获取退库单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsStockReturnOrderOutput> Get([FromQuery] QueryeWmsStockReturnOrderInput input)
        {
            return (await _wmsStockReturnOrderRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsStockReturnOrderOutput>();
        }

        /// <summary>
        /// 获取退库单列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsStockReturnOrderOutput>> List([FromQuery] WmsStockReturnOrderInput input)
        {
            return await _wmsStockReturnOrderRep.DetachedEntities.ProjectToType<WmsStockReturnOrderOutput>().ToListAsync();
        }    
         /// <summary>
        /// Excel模板导入退库单功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsStockReturnOrder", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++) 
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object?>> data, out string sheetName);
            List<WmsStockReturnOrderOutput> wmsStockReturnOrderList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsStockReturnOrderOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wmsStockReturnOrderList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsStockReturnOrder>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if(!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsStockReturnOrder, WmsStockReturnOrderOutput>(selectKeys);
            List<WmsStockReturnOrder> updates = new();
            List<WmsStockReturnOrder> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wmsStockReturnOrderExistSubList = _wmsStockReturnOrderRep.Where(filter).Select(selector).ToList();
                    wmsStockReturnOrderExistSubList.ForEach(x => 
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }
                foreach (var wmsStockReturnOrder in wmsStockReturnOrderList) 
                {
                    if (wmsStockReturnOrder.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wmsStockReturnOrder.Adapt<WmsStockReturnOrder>());
                    }
                    else 
                    {
                        adds.Add(wmsStockReturnOrder.Adapt<WmsStockReturnOrder>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wmsStockReturnOrderRep.Update(x));
                

                var maxId = _wmsStockReturnOrderRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);    
                Db.GetDbContext().Set<WmsStockReturnOrder>().AddRange(adds);  
                Db.GetDbContext().SaveChanges();
               
            }
            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载退库单的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsStockReturnOrder", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
        /// <summary>
        /// 根据退库单查询参数导出Excel
        /// </summary>
        /// <param name="input">退库单查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WmsStockReturnOrderSearchNonPage input)
        {
            var wmsStockReturnOrderList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wmsStockReturnOrderList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers, 
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsStockReturnOrder", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else 
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
